from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy
import time

# 配置 Appium 连接参数
options = UiAutomator2Options()
options.automation_name = "uiautomator2"
options.platform_name = "Android"
options.device_name = "6990f488"  # 使用真实设备的 ID
options.app_package = "com.android.settings"
options.app_activity = "com.android.settings.Settings"

# 连接 Appium 服务器
driver = webdriver.Remote('http://127.0.0.1:4723', options=options)

try:
    time.sleep(2)  # 等待设置页面加载

    # 向下滚动查找 "存储" 选项
    storage_option = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 
                                         'new UiScrollable(new UiSelector().scrollable(true))'
                                         '.scrollIntoView(new UiSelector().textContains("我的设备"))')
    storage_option.click()
    storage_option = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 
                                         'new UiScrollable(new UiSelector().scrollable(true))'
                                         '.scrollIntoView(new UiSelector().textContains("存储"))')
    storage_option.click()
    time.sleep(2)  # 等待存储页面加载

    # 提取存储信息（可用空间）
    storage_info = driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 
                                       'new UiSelector().resourceId("android:id/summary")').text
    print(f"存储信息: {storage_info}")

except Exception as e:
    print(f"发生错误: {e}")

finally:
    time.sleep(3)
    driver.quit()